package com.yami.shop.app.utils;

import cn.hutool.core.date.DateUtil;
import com.yami.shop.common.util.HttpClient;
import com.yami.shop.sys.model.SysConfig;
import com.yami.shop.sys.service.SysConfigService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class OfficalAccountTokenUtil {

    private static final String url ="https://api.weixin.qq.com/cgi-bin/token";

    @Autowired
    private SysConfigService sysConfigService;


    /**
     * 获取token,与当前时间比对。
     */
    public  String getToken(){
        //获取数据库中的token值
        SysConfig sysConfig = sysConfigService.getSysConfigByValue("offical_token", DateUtil.offsetHour(new Date(),2));
        if(sysConfig!=null){
            Date createTime = sysConfig.getCreateTime();
        }else{
            //重新申请token,保存进入数据库
            Map<String, String> params = new HashMap<>(8);
            params.put("appid", "wx53753d880795f1ff");
            params.put("secret","3f14a33384b365796a5a8edc6dfc7b5d");
            params.put("grant_type", "client_credential");
            String result = null;
            try {
                result = HttpClient.post(url,params);
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonObj = new JSONObject(result);
            String accessToken =  jsonObj.getString("access_token");
            sysConfig.setParamValue(accessToken);
            sysConfigService.saveOrUpdate(sysConfig);
        }
        return "success";
    }

}
